package prob;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.sun.grizzly.util.buf.Base64;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;

/**
 * Filter used to process the authorization
 * 
 * @author Xi
 * 
 */
public class MyFilter implements ContainerRequestFilter {

	// Exception thrown if user is unauthorized.
	private final static WebApplicationException unauthorized = new WebApplicationException(
			Response.status(Status.UNAUTHORIZED)
					.header(HttpHeaders.WWW_AUTHENTICATE,
							"Basic realm=\"realm\"")
					.entity("Page requires login.").build());

	// Exception thrown if the requested resource not included in the server
	private final static WebApplicationException notfound = new WebApplicationException(
			Response.status(Status.NOT_FOUND).entity("Error Message").build());

	@Override
	public ContainerRequest filter(ContainerRequest containerRequest)
			throws WebApplicationException {

		String path = containerRequest.getPath(true);
		// requested resource not included
		if (!path.equals("arbeit/log")) {
			saveClientInf(containerRequest);
			throw notfound;
		}

		// Get the authentication passed in HTTP headers parameters
		String auth = containerRequest.getHeaderValue("authorization");
		if (auth == null) {
			throw unauthorized;
		}

		auth = auth.replaceFirst("[Bb]asic ", "");
		// decode
		String userColonPass = Base64.base64Decode(auth);

		if (!userColonPass.equals("admin:admin")) {
			throw unauthorized;
		}

		return containerRequest;
	}

	/**
	 * Save the client information into log.txt file.
	 * 
	 * @param containerRequest
	 */
	public void saveClientInf(ContainerRequest containerRequest) {
		PrintWriter writer = null;
//		String logPath = getClass().getClassLoader().getResource(".").getPath()
//				.replaceAll("bin/", "log/log.txt");
		String logPath="log/log.txt";
		// read log file
		BufferedReader br = null;
		String everything = "";
		try {
			br = new BufferedReader(new FileReader(logPath));

			StringBuilder sb = new StringBuilder();
			String line;
			line = br.readLine();
			while (line != null) {
				sb.append(line);
				sb.append(System.lineSeparator());
				line = br.readLine();
			}
			everything = sb.toString();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// write log file
		try {
			writer = new PrintWriter(logPath, "UTF-8");
		} catch (FileNotFoundException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		writer.println(everything + "resource: "
				+ containerRequest.getAbsolutePath() + "; agent: "
				+ containerRequest.getHeaderValue("user-agent"));
		writer.close();
	}
}